<?php

namespace App\Http\Controllers\Socket;

use App\Models\UsersChatRecords;
use App\Http\Controllers\Controller;
use App\Repositories\Cache\LastMsgCache;
use App\Repositories\WebSocket\ClientManager;
use App\Repositories\WebSocket\UnreadTalk;
use Illuminate\Support\Facades\Log;
use SwooleTW\Http\Websocket\Facades\Websocket;

class NotifyController extends Controller
{
    /**
     * 未读消息类
     *
     * @var UnreadTalk
     */
    private $unreadTalk;

    /**
     * 客户端Fd管理
     *
     * @var ClientManager
     */
    private $clientManager;

    public function __construct()
    {
        $this->unreadTalk = new UnreadTalk();
        $this->clientManager = new ClientManager();
    }
    /**
     * 聊天对话消息
     *
     * @param $webSocket
     * @param array $msgData 接收数据
     * @return bool
     */
    public function talk($webSocket, $msgData)
    {
        Log::info("收到{{$msgData['send_user']}}");
        $result = UsersChatRecords::create([
            'user_id' => $msgData['send_user'],
            'receive_id' => $msgData['receive_user'],
            'content' => htmlspecialchars($msgData['text_message']),
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        if (!$result) {
            return false;
        }

        //获取消息推送的客户端
        $msg_text = mb_substr($result->content, 0, 30);
        // 缓存最后一条消息
        LastMsgCache::set([
            'text' => $msg_text,
            'created_at' => $result->created_at
        ], $msgData['receive_user'], $msgData['send_user']);

        $clientFds = array_unique(array_merge(
            $this->clientManager->findUserIdFds($msgData['receive_user']),
            $this->clientManager->findUserIdFds($msgData['send_user'])
        ));

        // 设置好友消息未读数
        $this->unreadTalk->setInc($result->receive_id, $result->user_id);

        if ($result->content) {
            $result->content = replace_url_link($result->content);
        }
        Websocket::to($clientFds)->emit("event_talk", [
            'send_user' => $msgData['send_user'],
            'receive_user' => $msgData['receive_user'],
            'source_type' => 1,
            'data' => [
                "id" => $result->id,
                "user_id" => $result->user_id,
                "receive_id" => $result->receive_id,
                "content" => $result->content,
                "created_at" => $result->created_at,
            ]
        ]);
    }
}
